#include "gamecoin.h"
#include <QDebug>

GameCoin::GameCoin(QString img, QWidget *parent)
    : QPushButton(parent)
    , m_isAnimation(false)
    , m_isWin(false)
    , m_minIndex(1)
    , m_maxIndex(8)
{
    //
    if(img != "")
    {
        QPixmap normalPix;
        bool ret = normalPix.load(img);
        if (ret)
        {
            QSize pSize(normalPix.width(), normalPix.height());
            this->setFixedSize(pSize);
            this->setStyleSheet("QPushButton{border:0px}");
            this->setIcon(normalPix);
            this->setIconSize(pSize);
        }
    }
    //定时器
    m_timerToBack = new QTimer(this);
    m_timerToFront = new QTimer(this);
    connect(m_timerToBack, &QTimer::timeout, this, [=](){
        QString imgCoinStr = QString(":/res/Coin000%1.png").arg(m_minIndex++);
//        qDebug() << "back imgCoinStr : " << imgCoinStr;
        QPixmap imgPix;
        bool retImg = imgPix.load(imgCoinStr);
        if(retImg)
        {
            QSize pSize(imgPix.width(), imgPix.height());
            this->setFixedSize(pSize);
            this->setStyleSheet("QPushButton{border:0px}");
            this->setIcon(imgPix);
            this->setIconSize(pSize);
        }
        if(m_minIndex > m_maxIndex)
        {
            m_minIndex = 1;
            m_timerToBack->stop();
            m_isAnimation = false;
        }
    });
    connect(m_timerToFront, &QTimer::timeout, this, [=](){
        QString imgCoinStr = QString(":/res/Coin000%8.png").arg(m_maxIndex--);
//        qDebug() << "front imgCoinStr : " << imgCoinStr;
        QPixmap imgPix;
        bool retImg = imgPix.load(imgCoinStr);
        if(retImg)
        {
            QSize pSize(imgPix.width(), imgPix.height());
            this->setFixedSize(pSize);
            this->setStyleSheet("QPushButton{border:0px}");
            this->setIcon(imgPix);
            this->setIconSize(pSize);
        }
        if(m_maxIndex < m_minIndex)
        {
            m_maxIndex = 8;
            m_timerToFront->stop();
            m_isAnimation = false;
        }
    });
}

void GameCoin::changeFlag()
{
    if (m_flag == true)
    {
        m_timerToBack->start(30);
        m_flag = false;
    }
    else
    {
        m_timerToFront->start(30);
        m_flag = true;
    }
    m_isAnimation = true;

}

int GameCoin::posX() const
{
    return m_posX;
}

void GameCoin::setPosX(int newPosX)
{
    m_posX = newPosX;
}

int GameCoin::posY() const
{
    return m_posY;
}

void GameCoin::setPosY(int newPosY)
{
    m_posY = newPosY;
}

bool GameCoin::flag() const
{
    return m_flag;
}

void GameCoin::setFlag(bool newFlag)
{
    m_flag = newFlag;
}

bool GameCoin::isWin() const
{
    return m_isWin;
}

void GameCoin::setIsWin(bool newIsWin)
{
    m_isWin = newIsWin;
}

void GameCoin::mousePressEvent(QMouseEvent *e)
{
    if (m_isWin == true || m_isAnimation == true)
    {
        return;
    }
    else
    {
        return QPushButton::mousePressEvent(e);
    }
}
